package com.cgtong.android.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.adapter.ProblemsAdapter;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.bean.SimpleResult;
import com.cgtong.android.callback.DiffCallBack;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.TimeLimitContract;
import com.cgtong.android.mvp.presenter.TimeLimitPresenter;
import com.cgtong.android.util.PostUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 超期案件
 */
public class TimeLimitActivity extends BaseTitleActivity implements TimeLimitContract.View {

    private static final String KEY_CURRENT_MONTH = "current_month";
    @BindView(R.id.time_limit_num_txt)
    TextView mTimeLimitNumTxt;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;

    private List<ProblemBean> mList;
    private ArrayList<ProblemBean> mNewList;
    private ProblemsAdapter mAdapter;

    private TimeLimitPresenter mPresenter;

    private String mCurrentMonth;

    public static void start(Context context, String month) {
        Intent starter = new Intent(context, TimeLimitActivity.class);
        starter.putExtra(KEY_CURRENT_MONTH, month);
        context.startActivity(starter);
    }

    @Override
    protected String getContentTitle() {
        return getString(R.string.title_time_limit);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_time_limit;
    }

    @Override
    protected void loadDataByNet() {
        PostUtil.postSuccessDelayed(loadService);
        mCurrentMonth = getIntent().getStringExtra(KEY_CURRENT_MONTH);

        mPresenter = new TimeLimitPresenter(this);
        mList = new ArrayList<>();
        mNewList = new ArrayList<>();
        initRecyclerView();
        mPresenter.httpExpiredNum(mCurrentMonth);
        mPresenter.httpProblemsData(mCurrentMonth, "", true);
    }


    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.httpProblemsData(mCurrentMonth, "", true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(TimeLimitActivity.this));
        mAdapter = new ProblemsAdapter(mList, this);
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(TimeLimitActivity.this, LinearLayoutManager.HORIZONTAL, R.drawable.shape_horizontal_divider));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                String maxTime = mAdapter.getItem(mAdapter.getItemCount() - 2).getCreateTime();
                mPresenter.httpProblemsData(mCurrentMonth, maxTime, false);
            }
        }, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProblemBean problemBean = mAdapter.getItem(position);
                boolean canDelete = false;
                boolean canEvaluate = false;
                if (((App) getApplicationContext()).isUserLogin()) {
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5 || problemBean.getStatus() == 7) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canDelete = true;
                    }
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canEvaluate = true;
                    }
                }
                ProblemDetailActivity.start(TimeLimitActivity.this, problemBean.getId(), canDelete, canEvaluate);

            }
        });
        //关注用户
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (App.getInstance().isUserLogin()) {
                    long userId = mAdapter.getItem(position).getCreateUserId();
                    if (userId == App.getInstance().getCurrentAccount().getUserId()) {
                        ToastUtils.showShort(getString(R.string.txt_cannot_follow_youself));
                        return;
                    }
                    mPresenter.follow(mAdapter.getItem(position).getCreateUserId(), position);
                } else {
                    Intent intent = new Intent(TimeLimitActivity.this, LoginActivity.class);
                    startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
                }
            }
        });
    }


    //--------回调---------
    @Override
    protected void onDataReloadByNet(View v) {
        mPresenter.httpExpiredNum(mCurrentMonth);
        mPresenter.httpProblemsData(mCurrentMonth, "", true);

    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);
    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }

    @Override
    public void onNullData() {
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);

    }

    @Override
    public void onHttpExpiredNumSuccess(SimpleResult result) {
        if (result.getCode() == 0) {
            mTimeLimitNumTxt.setText(String.format(getString(R.string.txt_time_limit_format), result.getData()));
        } else {
            ToastUtils.showShort(result.getMsg());
        }
    }

    @Override
    public void onError(ApiException e) {
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
    }

    @Override
    public void onHttpProblemsDataSuccess(List<ProblemBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        if (isRefresh) {
            mNewList.clear();
            mAdapter.setNewData(datas);
            mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
        } else {
            mAdapter.addData(datas);
        }
        mNewList.addAll(datas);//比较集合不同的List
        mAdapter.loadMoreComplete();
    }

    @Override
    public void onFollowSuccess(long id, int position, ApiResult result) {
        LogUtils.d("onfollowsuccess position = " + position + " newlist = " + mNewList.size() + " list = " + mList.size() + " adapter = " + mAdapter.getData().size());
        if (result.getCode() == 0) {
            List<ProblemBean> beanList = mAdapter.getData();
            for (int i = 0; i < beanList.size(); i++) {
                ProblemBean bean = beanList.get(i);
                if (bean.createUserId == id) {
                    ProblemBean newProblemBean = bean.cloneAll(bean);
                    if (newProblemBean.isCreateUserAttention == 1) {
                        newProblemBean.isCreateUserAttention = 0;
                    } else {
                        newProblemBean.isCreateUserAttention = 1;
                    }
                    mNewList.set(i, newProblemBean);
                }
            }

//            ProblemBean problemBean = mAdapter.getItem(position);
//            ProblemBean newProblemBean = problemBean.cloneAll(problemBean);
            if ("1".equals(result.getMsg())) {
                //关注成功
//                ToastUtils.showShort("关注成功！");
//                newProblemBean.setIsCreateUserAttention(1);
            } else {
                //取消关注成功
//                ToastUtils.showShort("取消关注成功！");
//                newProblemBean.setIsCreateUserAttention(0);
            }
//            mNewList.set(position, newProblemBean);

            DiffUtil.DiffResult diffResult = DiffUtil
                    .calculateDiff(new DiffCallBack(mAdapter.getData(), mNewList),
                            false);
            diffResult.dispatchUpdatesTo(mAdapter);

            mAdapter.setAllNewData(mNewList);

            mNewList.clear();
            mNewList.addAll(mAdapter.getData());
        } else {
            ToastUtils.showShort(result.getMsg());
        }
    }


}
